package cc.shacocloud.mirage.core;

import cc.shacocloud.mirage.bean.ClassScanner;
import cc.shacocloud.mirage.bean.ConditionHandler;
import cc.shacocloud.mirage.bean.ConfigurableBeanFactory;
import cc.shacocloud.mirage.bean.impl.ClassPathScanner;
import cc.shacocloud.mirage.core.impl.ApplicationAnnotationConditionHandler;
import cc.shacocloud.mirage.env.ConfigurableEnvironment;
import cc.shacocloud.mirage.utils.ClassUtil;
import org.jetbrains.annotations.NotNull;

/**
 * 通用的的应用上下文
 * <p>
 * 通过扫描 {@link cc.shacocloud.mirage.bean.bind.Component} 标识的类进行装载
 *
 * @author 思追(shaco)
 * @see cc.shacocloud.mirage.bean.AnnotationBeanFactory
 */
public class GenericApplicationContext extends AbstractApplicationContext {
    
    /**
     * 应用类加载器
     */
    private final ClassLoader classLoader;
    
    public GenericApplicationContext() {
        this(ClassUtil.getDefaultClassLoader());
    }
    
    public GenericApplicationContext(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }
    
    @NotNull
    @Override
    protected ConfigurableBeanFactory doBeanFactory() {
        ClassScanner classScanner = new ClassPathScanner(classLoader);
        ConditionHandler conditionHandler = new ApplicationAnnotationConditionHandler(this);
        ConfigurableBeanFactory beanFactory = new GenericApplicationBeanFactory(classScanner, conditionHandler, this);
        
        // 初始化内置对象
        initBuiltInObjects(beanFactory);
        
        return beanFactory;
    }
    
    @NotNull
    @Override
    protected ConfigurableEnvironment doEnvironment() {
        return new GenericApplicationEnvironment(this);
    }
    
    @NotNull
    @Override
    protected ApplicationEventMulticaster doEventMulticaster() {
        return new ApplicationEventMulticasterImpl();
    }
    
    /**
     * 初始化内置对象
     */
    protected void initBuiltInObjects(@NotNull ConfigurableBeanFactory beanFactory) {
    }
    
}
